package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.LoadMoreListView;
import com.shwread.android.ui.customview.LoadMoreListView.OnLoadMoreListener;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.JSONUtil;

import org.apache.http.Header;
import org.json.JSONException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import logic.bean.GoodsBaseInfo;
import logic.bean.GoodsInfoColumn;
import logic.constants.DefaultConsts;
import logic.util.MoneyUtil;
import logic.util.NetworkUtil;
import logic.util.PicassoUtil;
import logic.util.Util;
import logic.util.Utils;


public class GoodsSearchActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener,
        OnItemClickListener
{
	
	@SuppressLint ("HandlerLeak")
	private Handler              handler      = new Handler()
	                                          {
		                                          
		                                          @Override
		                                          public void handleMessage(Message msg) {
			                                          switch (msg.what) {
														  case 100:
															  lvGoods.onLoadMoreComplete();
															  if (goodsList.size() > 0)
															  {
																  
																  rlayGoodsSearchBlackBg.setVisibility(View.GONE);
																  rlayGoodsSearchResult.setVisibility(View.VISIBLE);
																  lvGoods.setVisibility(View.VISIBLE);
																  tvNoGoods.setVisibility(View.GONE);
																  goodsAdapter.notifyDataSetChanged();
																  TextIsChange = false;
																  btnSearch.setText("取消");
															  }
															  else
															  {
																  rlayGoodsSearchBlackBg.setVisibility(View.GONE);
																  rlayGoodsSearchResult.setVisibility(View.VISIBLE);
																  tvNoGoods.setVisibility(View.VISIBLE);
																  lvGoods.setVisibility(View.GONE);
															  }
															  
															  break;
														  case 101:
															  rlayGoodsSearchBlackBg.setVisibility(View.GONE);
															  rlayGoodsSearchResult.setVisibility(View.VISIBLE);
															  tvNoGoods.setVisibility(View.VISIBLE);
															  lvGoods.setVisibility(View.GONE);
															  Util.showToast(mContext, (String) msg.obj);
															  break;
														  default:
															  break;
													  }
												  }
												  
	                                          };
	
	private GoodsInfoColumn      resultInfo;
	private List<GoodsBaseInfo>  goodsList;
	private GoodsBoxAdapter      goodsAdapter;
	private Context              mContext;
	private TextView             tvNoGoods;
	private LoadMoreListView     lvGoods;
	private RelativeLayout       rlayGoodsSearchBlackBg, rlayGoodsSearchResult;
	private static boolean       TextIsChange = false;
	private Button               btnSearch, btnClear;
	private ImageView            ivIcon;
	private AutoCompleteTextView autotvGoodsName;
	public int                   currentPage  = 1;
	public int                   length       = 10;
	public int                   totalPage    = 1;
	public String                condition;
	
	// 隐藏系统输入法
	InputMethodManager           mInputMethodManager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.book_search);
		mContext = this;
		
		initView();
		initData();
		setListener();
	}
	
	private void setListener() {
		ivIcon.setOnClickListener(this);
		btnClear.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		autotvGoodsName.addTextChangedListener(new TextWatcher()
		{
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				if (TextUtils.isEmpty(arg0))
				{
					TextIsChange = false;
					btnClear.setVisibility(View.GONE);
					btnSearch.setText("取消");
				}
				else
				{
					TextIsChange = true;
					btnClear.setVisibility(View.VISIBLE);
					btnSearch.setText("搜索");
				}
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
			}
		});
		lvGoods.setOnItemClickListener(this);
		lvGoods.setOnLoadMoreListener(new OnLoadMoreListener()
		{
			
			@Override
			public void onLoadMore() {
				if (totalPage >= currentPage)
				{
					currentPage++;
					ActionHelp.qryAllEpGoods(mContext, condition, currentPage, length, new GoodsHandler2());
				}
				else
				{
					lvGoods.onLoadMoreComplete();
				}
			}
		});
	}
	
	private void initView() {
		ivIcon = (ImageView) findViewById(R.id.book_read_search_searchbox_icon_iv);
		btnClear = (Button) findViewById(R.id.book_read_search_searchbox_clear_btn);
		btnSearch = (Button) findViewById(R.id.book_read_search_search_btn);
		autotvGoodsName = (AutoCompleteTextView) findViewById(R.id.book_read_search_searchbox_edit_autotv);
		autotvGoodsName.setHint("商品名称");
		
		tvNoGoods = (TextView) findViewById(R.id.book_search_result_no_books_tv);
		tvNoGoods.setText("没有找到商品哦");
		lvGoods = (LoadMoreListView) findViewById(R.id.book_search_result_books_lv);
		rlayGoodsSearchBlackBg = (RelativeLayout) findViewById(R.id.book_search_black_rlay);
		rlayGoodsSearchResult = (RelativeLayout) findViewById(R.id.book_search_result_rlay);
		rlayGoodsSearchBlackBg.setVisibility(View.VISIBLE);
		mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		Util.showInputMethodManager(this);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.book_read_search_searchbox_edit_autotv:
				break;
			case R.id.book_read_search_searchbox_clear_btn:
				autotvGoodsName.setText("");
				rlayGoodsSearchBlackBg.setVisibility(View.VISIBLE);
				rlayGoodsSearchResult.setVisibility(View.GONE);
				break;
			case R.id.book_read_search_search_btn:
				if (TextIsChange)
				{
					Util.hideInputMethodManager(this, autotvGoodsName);
					searchGoods();
				}
				else
				{// 取消搜索
					onBackPressed();
					// 隐藏系统输入法
					Util.hideInputMethodManager(this, autotvGoodsName);
					
					rlayGoodsSearchBlackBg.setVisibility(View.VISIBLE);
					rlayGoodsSearchResult.setVisibility(View.GONE);
					tvNoGoods.setVisibility(View.GONE);
					lvGoods.setVisibility(View.GONE);
				}
				break;
		}
		
	}
	
	private void searchGoods() {
		condition = autotvGoodsName.getText().toString().trim();
		currentPage = 1;
		if (Util.isEmpty(condition))
		{
			Util.showToast(mContext, "搜索内容不能为空哦");
		}
		else if (NetworkUtil.isNetAvailable(mContext))
		{
			ActionHelp.qryAllEpGoods(mContext, condition, currentPage, length, new GoodsHandler1());
		}
		else
		{
			new NetworkDialog(mContext).show();
		}
		
	}
	
	private class GoodsHandler1
	        extends
	        ObjectHttpResponseHandler<GoodsInfoColumn>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			if (statusCode > 1000)
			{
				try
				{
					Message msg = Message.obtain();
					msg.what = 101;
					msg.obj = JSONUtil.getString(responseString);
					handler.sendMessage(msg);
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
				
			}
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, GoodsInfoColumn object, String responseString) {
			resultInfo = object;
			totalPage = resultInfo.getPageDto().getTotalPage();
			if (goodsList.size() > 0) goodsList.clear();
			goodsList.addAll(resultInfo.getGoodsList());
			handler.sendEmptyMessage(100);
		}
		
		@Override
		public Type getType() {
			return new TypeToken<GoodsInfoColumn>()
			{
			}.getType();
		}
		
	}
	
	private class GoodsHandler2
	        extends
	        ObjectHttpResponseHandler<GoodsInfoColumn>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			if (statusCode > 1000)
			{
				try
				{
					Message msg = Message.obtain();
					msg.what = 101;
					msg.obj = JSONUtil.getString(responseString);
					handler.sendMessage(msg);
				}
				catch (JSONException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, GoodsInfoColumn object, String responseString) {
			resultInfo = object;
			goodsList.addAll(resultInfo.getGoodsList());
			handler.sendEmptyMessage(100);
		}
		
		@Override
		public Type getType() {
			return new TypeToken<GoodsInfoColumn>()
			{
			}.getType();
		}
		
	}
	
	private class GoodsBoxAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			return goodsList.size();
		}
		
		@Override
		public Object getItem(int position) {
			return goodsList.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(GoodsSearchActivity.this).inflate(R.layout.goods_box_list_item, parent, false);
				viewHolder.ivGoodsCover = (ImageView) convertView.findViewById(R.id.good_box_list_item_cover_iv);
				viewHolder.tvGoodIntro = (TextView) convertView.findViewById(R.id.good_box_list_item_intro_tv);
				viewHolder.tvDiscountPrice = (TextView) convertView.findViewById(R.id.good_box_list_item_discount_price_tv);
				viewHolder.tvOriginalPrice = (TextView) convertView.findViewById(R.id.good_box_list_item_original_price_tv);
				viewHolder.tvSaleNumber = (TextView) convertView.findViewById(R.id.good_box_list_item_number_tv);
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			GoodsBaseInfo info = (GoodsBaseInfo) getItem(position);
			viewHolder.tvGoodIntro.setText(info.getTitle());
			//如果为空显示默认图片
			if (Utils.isEmpty(info.getCoverUrl()))
			{
				viewHolder.ivGoodsCover.setBackgroundResource(R.drawable.bg_small_image);
			}
			else
			{
//				viewHolder.ivGoodsCover.setImageUrl(info.getCoverUrl());
				PicassoUtil.load(mContext, info.getCoverUrl(), R.drawable.bg_small_image, viewHolder.ivGoodsCover);
			}
			//如果活动价为0，说明该商品没有参加活动，只显示原价
			if (info.getActivityPrice() == 0)
			{
				viewHolder.tvDiscountPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(info.getSalePrice(), 100.0)));
				viewHolder.tvOriginalPrice.setVisibility(View.GONE);
			}
			else
			{
				viewHolder.tvDiscountPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(info.getActivityPrice(), 100.0)));
				viewHolder.tvOriginalPrice.setText(" ¥" + Double.toString(info.getSalePrice()));
				viewHolder.tvOriginalPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//设置中画线
				viewHolder.tvOriginalPrice.setVisibility(View.VISIBLE);
				
			}
			if (info.getSaleNum() == 0)
			{
				viewHolder.tvSaleNumber.setText("新品上市");
			}
			else
			{
				viewHolder.tvSaleNumber.setText(Long.toString(info.getSaleNum()) + "人已经购买");
			}
			
			return convertView;
		}
	}
	
	class ViewHolder
	{
		private ImageView ivGoodsCover;   //商品封面URL
		private TextView       tvGoodIntro;    //商品介绍
		private TextView       tvDiscountPrice; //商品打折后的价格
		private TextView       tvOriginalPrice; //商品原价
		private TextView       tvSaleNumber;   //商品卖出的数量
	}
	
	private void initData() {
		goodsList = new ArrayList<GoodsBaseInfo>();
		goodsAdapter = new GoodsBoxAdapter();
		lvGoods.setAdapter(goodsAdapter);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		if (mAService != null) mAService.stopAService();
		super.onDestroy();
	}
	
	@Override
	public Handler getUIHandler() {
		return handler;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = new Intent(GoodsSearchActivity.this, NewGoodsMainActivity.class);
		intent.putExtra(DefaultConsts.GOODS_ID_TO_WAP, goodsList.get(position).getGoodsId());
		intent.putExtra(DefaultConsts.GOODS_DETAIL_URL_TO_WAP, goodsList.get(position).getDetailUrl());
		intent.putExtra(DefaultConsts.GOODS_BASE_URL_TO_WAP, goodsList.get(position).getBaseUrl());
		startActivity(intent);
	}
	
}
